package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
	
	private final UserMapper userMapper;
	private final WeChatProperties weChatProperties;
	
	public UserServiceImpl(UserMapper userMapper, WeChatProperties weChatProperties) {
		this.userMapper = userMapper;
		this.weChatProperties = weChatProperties;
	}
	
	@Override
	public Result userLogin(UserLoginDTO loginDTO) {
		if (loginDTO == null || loginDTO.getCode() == null) {
			return Result.error(MessageConstant.INCORRECT_PARAMETERS);
		}
		String url = "https://api.weixin.qq.com/sns/jscode2session";
		Map<String, String> bodyMap = new HashMap<>();
		bodyMap.put("appid", weChatProperties.getAppid());
		bodyMap.put("secret", weChatProperties.getSecret());
		bodyMap.put("js_code", loginDTO.getCode());
		bodyMap.put("grant_type", "authorization_code");
		String response = HttpClientUtil.doGet(url, bodyMap);
		Map responseMap = JSON.parseObject(response, Map.class);
		String openId = (String) responseMap.get("openid");
		if (openId == null) {
			return Result.error(MessageConstant.LOGIN_FAILED);
		}
		User user = userMapper.getUserByOpenId(openId);
		if (user == null) {
			user = User.builder()
					.openid(openId)
					.createTime(LocalDateTime.now())
					.build();
			userMapper.insert(user);
		}
		UserLoginVO loginVO = UserLoginVO.builder()
				.id(user.getId())
				.openid(user.getOpenid())
				.token(JwtUtil.getToken(user.getId()))
				.build();
		return Result.success(loginVO);
	}
}
